package by.dezhits.makeanote;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import by.dezhits.makeanote.content.contract.NotesContract;

public class NoteActivity extends Activity {

	public static final int NEW_NOTE = 0;
	public static final int REWITE_NOTE = 1;
	
	private EditText mEditTextTitle;
	private EditText mEditTextText;
	
	private Integer id;
	private String title;
	private String text;
	private String date;
	private String folder;
	private String closed;
	
	private final static String datePattern = "yyyy.MM.dd HH:mm:ss"; 
	private final static SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern, Locale.US);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_note);
		Intent intent =getIntent(); 
		int requestCode = intent.getIntExtra(
				getString(R.string.request_code), NEW_NOTE);
		mEditTextTitle = (EditText) findViewById(R.id.tv_title);
		mEditTextText = (EditText) findViewById(R.id.tv_text);
		folder = intent.getStringExtra(getString(R.string.folder));
		closed = intent.getStringExtra(getString(R.string.closed));
		if (requestCode == NEW_NOTE) {
			id = null;
		} else if (requestCode == REWITE_NOTE) {
			id = intent.getIntExtra(getString(R.string.id),0);
			title = intent.getStringExtra(getString(R.string.title));
			text = intent.getStringExtra(getString(R.string.text));
			mEditTextTitle.setText(title);
			mEditTextText.setText(text);
		}
	}

	public void saveNote(View v) {
		if (!TextUtils.isEmpty((title = mEditTextTitle.getText().toString()))) {
			ContentValues values = new ContentValues();
			values.put(getString(R.string.id), id);
			values.put(getString(R.string.folder), folder);
			values.put(getString(R.string.closed), closed);
			values.put(getString(R.string.title), title);
			if (!TextUtils.isEmpty((text = mEditTextText.getText().toString()))) {
				values.put(getString(R.string.text), text);
			}
			date = dateFormat.format(new Date());
			values.put(getString(R.string.date), date);
			values.put(getString(R.string.should_notify), true);
			getContentResolver().insert(NotesContract.NotesColumns.CONTENT_URI,
					values);
			finish();
		} else {
			Toast.makeText(this, "Cannot save notes without title, sorry",
					Toast.LENGTH_LONG).show();
		}
	}

}
